package com.zhs.study.threadpool;

import com.zhs.study.pojo.User;
import com.zhs.study.util.ThreadPoolUtil;

import javax.xml.crypto.Data;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author zhenghuisheng
 * @date : 2023/5/12
 */
public class SingleThread {
    public static void main(String[] args) throws Exception {
        List<User> list = new ArrayList<>();
        //单例线程池，速度慢，并且内部使用链表阻塞队列，队列可以容纳的大小为整形最大值，容易出现OOM
        ExecutorService executorService1 = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 50; i++) {
            byte[] bytes = new byte[1024 * 1024];
            User u = new User();
            list.add(u);
            executorService1.submit(new Task("===SingleThreadExecutor===单例线程池 " + new Date()));
            Thread.sleep(20);
        }
        //固定线程池,内部使用链表阻塞队列，队列可以容纳的大小为整形最大值，容易出现OOM
        ExecutorService executorService2 = Executors.newFixedThreadPool(4);
        for (int i = 0; i < 50 ; i++) {
            User u = new User();
            list.add(u);
            executorService2.submit(new Task("===FixedThreadPool===固定线程池 " + new Date()));
            Thread.sleep(20);
        }
        //缓存线程池，内部的最大线程数为整型最大值，容易出现OOM
        ExecutorService executorService3 = Executors.newCachedThreadPool();
        for (int i = 0; i < 50; i++) {
            User u = new User();
            list.add(u);
            executorService3.submit(new Task("===CachedThreadPool===缓存线程池 " + new Date()));
            Thread.sleep(20);
        }
        //延迟线程池,内部设置的最大线程数也是整型最大值，也容易出现OOM
        ExecutorService executorService4 = Executors.newScheduledThreadPool(10);
        for (int i = 0; i < 50; i++) {
            User u = new User();
            list.add(u);
            executorService4.submit(new Task("===ScheduledThreadPool===缓存线程池 " + new Date()));
            Thread.sleep(20);
        }
        //自定义线程池
        ThreadPoolExecutor threadPool = ThreadPoolUtil.getThreadPool();
        for (int i = 0; i < 50; i++) {
            User u = new User();
            list.add(u);
            threadPool.submit(new Task("===CustomThreadPool===自定义线程池 " + new Date()));
            Thread.sleep(20);
        }
    }

    static class Task implements Runnable{

        private String poolType;

        public Task(String poolType){
            this.poolType = poolType;
        }
        @Override
        public void run() {
                System.out.println("当前线程名称为" + poolType + Thread.currentThread().getName());
        }
    }
}


